<?php
namespace app\console\controller;

use app\api\controller\Aliyun;
use app\common\WechatPay;
use app\model\MemberBrokerage;
use app\model\MemberWithdraw as SelfModel;
use app\model\Member;


use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\facade\Route;
use think\facade\View;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Cookie;
class MemberWithdraw extends Base
{



    public function initialize()
    {
        parent::initialize();
        $this->model = "\app\model\MemberWithdraw";
        $this->list_rows = 100;
        
    }
    public function select()
    {
            $member = Member::where([['status', '=', 1]])->order(['sort' => 'asc', 'id' => 'desc'])->select()->toArray();
            View::assign('member', $member);
    }

    public function index()
    {

        $param = Request::param();


        $data = SelfModel::withSearch(array_keys($param), $param)->order(['id'=>'desc'])->paginate(['query' => $param, 'list_rows' => 20])
            ->each(function ($item, $key) {
               // $item['is_check'] = (new WechatPay('mobile'))->withdraw_check($item['order_number'],$item['withdraw_no']);
        });

        $this->select();
        return View::fetch('', ['data' => $data]);
    }

    /*
     * 提现申请
     */
    public function update()
    {
        $param = \request()->param();
        $info = (new SelfModel())->find($param['id']);
        if($info['audit_status'] != 1){
            fail('当前不是待审核状态');
        }
        if ($this->request->isPost()) {
            if($param['audit_status'] == 2){
                $param['audit_time'] = date('Y-m-d H:i:s');
                if($param['type_id'] == 1){
                    //微信

                }
                if($param['type_id'] == 2){
                    //支付宝
                    $ret = (new Aliyun())->withdraw($param['order_number'],$param['brokerage'],$param['withdraw_no'],$param['withdraw_name']);//体现成功直接修改状态 失败退回

                    if($ret['code'] != 200){ //失败
                        $data['audit_status'] = 3;
                        $data['error_msg'] = $ret['msg'].' 账户已恢复操作前'.$param['before'];
                        //Member::where('id',$param['member_id'])->update(['brokerage' =>$param['before']]);//不可以多次提现 固定变量值写死 如果还继续分佣会写错
                        Member::where('id',$param['member_id'])->inc('brokerage',$param['brokerage'])->update();//不可以多次提现 固定变量值写死 如果还继续分佣会写错
                        $ret = $info->save($data);
                        if ($ret !== false) {
                            jump('提现失败', Route::buildUrl('index'));
                        }
                    }
                }
                if($param['type_id'] == 3){
//                    $order_number = order_number();
                    //MemberBrokerage::saveData($info['member_id'],$info['member_id'],'提现手续费','-',$info['add_brokerage'],$info['brokerage']+$info['add_brokerage'],$order_number);

                }

                $ret = $info->save($param);
                if ($ret !== false) {
                    win('提现成功', Route::buildUrl('index'));
                }
            }
            if($param['audit_status'] == 3){
                if(empty($param['error_msg'])){
                    fail('请填写失败原因');
                }
                MemberBrokerage::saveData($info['member_id'],$info['member_id'],'提现失败:'.$param['error_msg'],'+',$info['brokerage'],$info['brokerage'],$info['order_number']);
                $ret = $info->save($param);
                if ($ret !== false) {
                    win('佣金返还', Route::buildUrl('index'));
                }
                fail('失败');
            }

            if($param['audit_status'] == 1){

                $ret = $info->save($param);
                if ($ret !== false) {
                    win('修改成功', Route::buildUrl('index'));
                }
                fail('失败');
            }

//            if(!empty($param['audit_status']) && $param['audit_status'] == 3){
//
//            }

        }

        $this->select();

        return View::fetch('create', ['info' => $info]);
    }

    public function audit_status()
    {
        Db::startTrans();
        try {
            $param = Request::param();
            $info = $this->model::where('id', $param['id'])->where('audit_status', 1)->find();
            if(empty($info)){
                return json(['code' => 400, 'msg' => '状态不是待审核']);
            }
            if ($info['type_id'] == 2) {
                //支付宝
                $ret = (new Aliyun())->withdraw($info['order_number'], $info['brokerage'], $info['withdraw_no'], $info['withdraw_name']);//体现成功直接修改状态 失败退回

                if ($ret['code'] != 200) { //失败
                    if($ret['msg'] == 40004){
                        return json(['code' => $ret['code'], 'msg' => $ret['msg']]);//如果余额不足直接停止;不修改 同一个订单号转账OK了再次转账还是返回10000但是不继续转钱了
                    }
                    $data['audit_status'] = 3; //如果账号或者密码错误就得返还
                    $data['error_msg'] = $ret['msg'];
                    MemberBrokerage::saveData($info['member_id'],$info['member_id'],'佣金返还','+',$info['brokerage'],'','');
                    Db::commit();
                    $mw_ret = $info->save($data);
                    return json(['code' => 401, 'msg' => $ret['msg']]);//401审核失败刷新
                    //Member::where('id',$param['member_id'])->update(['brokerage' =>$param['before']]);//不可以多次提现 固定变量值写死 如果还继续分佣会写错
                }

            }
            if ($info['type_id'] == 1) {
               // $order_number = order_number();
               // $param['order_number'] = $order_number;
                $ret= (new WechatPay('mobile'))->withdraw($info['order_number'],$info['withdraw_no'],$info['brokerage']-$info['add_brokerage']);

                if($ret !== true){ //错误信息;

                    $this->model::where('id', $param['id'])->where('audit_status', 1)->update(['audit_status' => 3,'error_msg'=>$ret]);
                    MemberBrokerage::saveData($info['member_id'],$info['member_id'],'提现失败:'.$ret,'+',$info['brokerage'],$info['brokerage'],$info['order_number']);
                    Db::commit();
                    return json(['code' => 400, 'msg' => $ret]);
                }
            }
            if ($info['type_id'] == 3) {
                //$order_number = order_number();

            }
//            MemberBrokerage::saveData($info['member_id'],$info['member_id'],'佣金提现','-',$info['brokerage'],$info['brokerage'],$order_number);
            //MemberBrokerage::saveData($info['member_id'],$info['member_id'],'佣金提现','-',$info['brokerage'],$info['brokerage'],$order_number);
            $ret = $this->model::where('id', $param['id'])->where('audit_status', 1)->update(['audit_status' => 2]);
            Db::commit();
            if($ret){
                return json(['code' => 200, 'msg' => '审核成功'.($info['brokerage']-$info['add_brokerage'])]);
            }
            return json(['code' => 400, 'msg' => '审核修改失败了']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'msg' => $e->getMessage()]);
        }
    }

    public function export($filename='1.xlsx')
    {
        $filename = '会员提现导出';
        $param = $this->request->param();
        if(!empty($param['create_time'])){
            $filename .= ' '.$param['create_time'];
        }
        $filename .= '.xlsx';
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $header = ['ID','会员','提现方式','提现账号','提现佣金','实付佣金','提现姓名','提现银行','开户行地址','订单号','创建时间','提现状态'];
        foreach ($header as $kh => $vh){
            $sheet->setCellValueByColumnAndRow($kh+1,1, $vh);
        }
        $data = SelfModel::withSearch(array_keys($param), $param)->lock(true)->order(['id'=>'desc'])->select();
        foreach ($data as $k => $v){
            $sheet->setCellValueByColumnAndRow(1,1+$k+1, $v['id']);
            $sheet->setCellValueByColumnAndRow(2,1+$k+1, $v['member_mobile']);
            $sheet->setCellValueByColumnAndRow(3,1+$k+1, $v['type_title']);
            $sheet->setCellValueExplicitByColumnAndRow(4,1+$k+1, $v['withdraw_no'],DataType::TYPE_STRING);
            $sheet->setCellValueByColumnAndRow(5,1+$k+1, $v['brokerage']);
            $sheet->setCellValueByColumnAndRow(6,1+$k+1, $v['brokerage']-$v['add_brokerage']);
            $sheet->setCellValueByColumnAndRow(7,1+$k+1, $v['withdraw_name']);
            $sheet->setCellValueByColumnAndRow(8,1+$k+1, $v['withdraw_bank']);
            $sheet->setCellValueByColumnAndRow(9,1+$k+1, $v['withdraw_address']);
            $sheet->setCellValueByColumnAndRow(10,1+$k+1, $v['order_number']);
            $sheet->setCellValueByColumnAndRow(11,1+$k+1, $v['create_time']);
            $sheet->setCellValueByColumnAndRow(12,1+$k+1, $v['audit_title']);

        }
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        ob_end_flush();

    }

//    public function export(){
//        $config = [
//            'path' => public_path() // xlsx文件保存路径
//        ];
//        $excel  = new \Vtiful\Kernel\Excel($config);
//
//// fileName 会自动创建一个工作表，你可以自定义该工作表名称，工作表名称为可选参数
//        $filePath = $excel->fileName('tutorial01.xlsx', 'sheet1')
//            ->header(['Item', 'Cost'])
//            ->data([
//                ['Rent', 1000],
//                ['Gas',  100],
//                ['Food', 300],
//                ['Gym',  50],
//            ])
//            ->output();
//
//    }




}